package com.dddframework.security.infras.config;

import com.dddframework.security.domain.auth.component.ResourceAuthExceptionEntryPoint;
import com.dddframework.security.domain.thirdparty.component.ThirdPartyAuthenticationFilter;
import com.dddframework.security.domain.thirdparty.component.ThirdPartyAuthenticationProvider;
import com.dddframework.security.domain.auth.service.IUserDetailService;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 手机号登录配置入口
 *
 * @author zhouzx
 */
@Getter
@Setter
public class ThirdPartySecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    private AuthenticationEventPublisher eventPublisher;
    private AuthenticationSuccessHandler loginSuccessHandler;
    private IUserDetailService userService;
    private ThirdPartyProperties thirdPartyProperties;

    @Override
    public void configure(HttpSecurity http) {
        ThirdPartyAuthenticationFilter thirdPartyAuthenticationFilter = new ThirdPartyAuthenticationFilter();
        thirdPartyAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        thirdPartyAuthenticationFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
        thirdPartyAuthenticationFilter.setEventPublisher(eventPublisher);
        thirdPartyAuthenticationFilter.setAuthenticationEntryPoint(new ResourceAuthExceptionEntryPoint());
        ThirdPartyAuthenticationProvider thirdPartyAuthenticationProvider = new ThirdPartyAuthenticationProvider();
        thirdPartyAuthenticationProvider.setUserService(userService);
        thirdPartyAuthenticationProvider.setThirdPartyProperties(thirdPartyProperties);
        http.authenticationProvider(thirdPartyAuthenticationProvider).addFilterAfter(thirdPartyAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}